<template>
  <div class="contract-list">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>合同管理</h2>
      <p>合同信息查询与管理</p>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="合同名称">
          <el-input
            v-model="searchForm.ContractName"
            placeholder="请输入合同名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="供应商">
          <el-select
            v-model="searchForm.SupplierId"
            placeholder="请选择供应商"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="supplier in supplierOptions"
              :key="supplier.id"
              :label="supplier.supplierName"
              :value="supplier.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态">
          <el-select
            v-model="searchForm.Review"
            placeholder="请选择审核状态"
            clearable
            style="width: 150px"
          >
            <el-option label="已审核" :value="1" />
            <el-option label="未审核" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="action-card" shadow="never">
      <div class="action-buttons">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增合同
        </el-button>
        <el-button type="success" @click="handleExport" :loading="exportLoading">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
      </div>
    </el-card>

    <!-- 新增/编辑合同对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑合同' : '新增合同'"
      width="600px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        class="contract-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="合同名称" prop="contractName">
              <el-input
                v-model="formData.contractName"
                placeholder="请输入合同名称"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同编号" prop="contractCode">
              <el-input
                v-model="formData.contractCode"
                placeholder="系统自动生成"
                readonly
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="供应商" prop="supplierId">
              <el-input
                v-model="selectedSupplierName"
                placeholder="请选择供应商"
                readonly
                style="width: 100%"
                @click="handleSupplierSelect"
              >
                <template #suffix>
                  <el-icon class="el-input__icon" style="cursor: pointer">
                    <Search />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同价格" prop="contractPrice">
              <el-input-number
                v-model="formData.contractPrice"
                placeholder="请输入合同价格"
                :min="0"
                :precision="2"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="物料ID" prop="materialId">
              <el-input-number
                v-model="formData.materialId"
                placeholder="请输入物料ID"
                :min="1"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料数量" prop="materialCount">
              <el-input-number
                v-model="formData.materialCount"
                placeholder="请输入物料数量"
                :min="1"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="创建时间" prop="createTime">
              <el-date-picker
                v-model="formData.createTime"
                type="datetime"
                placeholder="请选择创建时间"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DDTHH:mm:ss.sssZ"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="更新时间" prop="updateTime">
              <el-date-picker
                v-model="formData.updateTime"
                type="datetime"
                placeholder="请选择更新时间"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DDTHH:mm:ss.sssZ"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否审核" prop="review">
              <el-radio-group v-model="formData.review">
                <el-radio :label="1">已审核</el-radio>
                <el-radio :label="0">未审核</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同状态" prop="state">
              <el-radio-group v-model="formData.state">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="附件信息" prop="accessory">
          <el-input
            v-model="formData.accessory"
            placeholder="请输入附件信息"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="备注" prop="desc">
          <el-input
            v-model="formData.desc"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            {{ isEdit ? '保存' : '新增' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table :data="tableData" v-loading="loading" stripe border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="contractName" label="合同名称" width="200">
          <template #default="{ row }">
            <el-link type="primary" @click="handleDetail(row)">
              {{ row.contractName }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="contractCode" label="合同编号" width="120" />
        <el-table-column prop="supplierName" label="供应商名称" width="180" />
        <el-table-column prop="supplierCode" label="供应商编码" width="120" />
        <el-table-column prop="supplierLevel" label="供应商等级" width="120">
          <template #default="{ row }">
            <el-tag :type="getSupplierLevelType(row.supplierLevel)">
              {{ row.supplierLevel }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="contractPrice" label="合同价格" width="120">
          <template #default="{ row }">
            ¥{{ row.contractPrice }}
          </template>
        </el-table-column>
        <el-table-column prop="materialCount" label="物料数量" width="100" />
        <el-table-column prop="review" label="审核状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.review === 1 ? 'success' : 'info'">
              {{ row.review === 1 ? '已审核' : '未审核' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="state" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.state === 1 ? 'success' : 'danger'">
              {{ row.state === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="320" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleDetail(row)">
              <el-icon><View /></el-icon>
              详情
            </el-button>
            <el-button type="success" size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button 
              v-if="row.review === 0" 
              type="warning" 
              size="small" 
              @click="handleSingleReview(row)"
              :loading="row.reviewLoading"
            >
              审核
            </el-button>
            <el-button 
              v-if="row.review === 1" 
              type="info" 
              size="small" 
              @click="handleCancelReview(row)"
              :loading="row.reviewLoading"
            >
              取消审核
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.pageindex"
          v-model:page-size="pagination.pagesize"
          :page-sizes="[6, 10, 20, 50, 100]"
          :total="pagination.totalCount"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 供应商选择对话框 -->
    <el-dialog
      v-model="supplierSelectVisible"
      title="选择供应商"
      width="800px"
      :close-on-click-modal="false"
      @close="handleSupplierSelectClose"
    >
      <!-- 搜索区域 -->
      <el-form :model="supplierSearchForm" :inline="true" class="supplier-search-form">
        <el-form-item label="供应商编号/名称">
          <el-input
            v-model="supplierSearchForm.keyword"
            placeholder="请输入供应商编号/名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="供应商等级">
          <el-select
            v-model="supplierSearchForm.supplierLevel"
            placeholder="请选择供应商等级"
            clearable
            style="width: 150px"
          >
            <el-option label="A级" value="A级" />
            <el-option label="B级" value="B级" />
            <el-option label="C级" value="C级" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSupplierSearch" :loading="supplierLoading">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleSupplierSearchReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 供应商表格 -->
      <el-table
        :data="supplierTableData"
        v-loading="supplierLoading"
        stripe
        border
        style="width: 100%"
        @row-click="handleSupplierRowClick"
        highlight-current-row
      >
        <el-table-column type="radio" width="60" align="center">
          <template #default="{ row }">
            <el-radio
              v-model="selectedSupplierId"
              :label="row.id"
              @change="handleSupplierRadioChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="id" label="序号" width="80" />
        <el-table-column prop="supplierCode" label="供应商编号" width="120" />
        <el-table-column prop="supplierName" label="供应商名称" width="200" />
        <el-table-column prop="supplierLevel" label="供应商等级" width="120">
          <template #default="{ row }">
            <el-tag :type="getSupplierLevelType(row.supplierLevel)">
              {{ row.supplierLevel }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="people" label="联系人" width="120" />
      </el-table>

      <!-- 分页 -->
      <div class="supplier-pagination">
        <el-pagination
          v-model:current-page="supplierPagination.pageindex"
          v-model:page-size="supplierPagination.pagesize"
          :page-sizes="[10, 20, 50, 100]"
          :total="supplierPagination.totalCount"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSupplierSizeChange"
          @current-change="handleSupplierCurrentChange"
        />
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleSupplierSelectClose">取消</el-button>
          <el-button type="primary" @click="handleSupplierConfirm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="合同详情"
      width="800px"
      :before-close="handleDetailClose"
    >
      <div v-if="currentDetail" class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="合同名称">
            <el-tag type="primary">{{ currentDetail.contractName }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="合同编号">
            <el-tag type="info">{{ currentDetail.contractCode }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="合同价格">
            <span class="amount-text">¥{{ currentDetail.contractPrice }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="物料数量">
            {{ currentDetail.materialCount }}
          </el-descriptions-item>
          <el-descriptions-item label="供应商名称">
            {{ currentDetail.supplierName }}
          </el-descriptions-item>
          <el-descriptions-item label="供应商编码">
            <el-tag type="success">{{ currentDetail.supplierCode }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="供应商等级">
            <el-tag :type="getSupplierLevelType(currentDetail.supplierLevel)">
              {{ currentDetail.supplierLevel }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="联系人">
            {{ currentDetail.people }}
          </el-descriptions-item>
          <el-descriptions-item label="联系电话">
            {{ currentDetail.phone }}
          </el-descriptions-item>
          <el-descriptions-item label="审核状态">
            <el-tag :type="currentDetail.review === 1 ? 'success' : 'info'">
              {{ currentDetail.review === 1 ? '已审核' : '未审核' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="合同状态">
            <el-tag :type="currentDetail.state === 1 ? 'success' : 'danger'">
              {{ currentDetail.state === 1 ? '启用' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatDateTime(currentDetail.createTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            {{ formatDateTime(currentDetail.updateTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="附件信息">
            {{ currentDetail.accessory || '无' }}
          </el-descriptions-item>
          <el-descriptions-item label="备注信息" :span="2">
            {{ currentDetail.desc || '无' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDetailClose">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Download, Edit, View } from '@element-plus/icons-vue'
import { getReadClient, getWriteClient } from '@/Urls/AxiosHelper'

// 使用正确的客户端
const r3 = getReadClient(0)
const w8 = getWriteClient(0)

// 接口类型定义
interface Contract {
  id: number
  contractName: string
  contractCode: string
  updateTime: string
  supplierId: number
  contractPrice: number
  createTime: string
  review: number
  desc: string
  accessory: string
  materialId: number
  materialCount: number
  isDelete: boolean
  supplierCode: string
  supplierName: string
  supplierLevel: string
  people: string
  state: number
  phone: string
  reviewLoading?: boolean // 审核按钮加载状态
}

interface Supplier {
  id: number
  supplierName: string
  supplierCode: string
  supplierLevel: string
  people: string
}

interface ApiResponse {
  data: {
    totalCount: number
    totalPage: number
    data: Contract[]
  }
  code: number
  message: string
}

// 响应式数据
const loading = ref(false)
const tableData = ref<Contract[]>([])
const exportLoading = ref(false)
const supplierOptions = ref<Supplier[]>([])
const supplierLoading = ref(false)

// 供应商选择对话框相关
const supplierSelectVisible = ref(false)
const supplierTableData = ref<Supplier[]>([])
const selectedSupplierId = ref<number | null>(null)
const selectedSupplierName = ref('')
const supplierSearchForm = reactive({
  keyword: '',
  supplierLevel: ''
})
const supplierPagination = reactive({
  pageindex: 1,
  pagesize: 10,
  totalCount: 0,
  totalPage: 0
})

// 详情相关
const detailVisible = ref(false)
const currentDetail = ref<Contract | null>(null)

// 新增/编辑对话框相关
const dialogVisible = ref(false)
const submitLoading = ref(false)
const formRef = ref()
const isEdit = ref(false)
const currentEditId = ref<number | null>(null)

// 搜索表单
const searchForm = reactive({
  ContractName: '',
  SupplierId: null as number | null,
  Review: null as number | null
})

// 分页数据
const pagination = reactive({
  pageindex: 1,
  pagesize: 6,
  totalCount: 0,
  totalPage: 0
})

// 表单数据
const formData = reactive({
  contractName: '',
  contractCode: '',
  supplierId: null as number | null,
  contractPrice: 0,
  materialId: null as number | null,
  materialCount: 1,
  createTime: '',
  updateTime: '',
  review: 0,
  state: 1,
  accessory: '',
  desc: ''
})

// 表单验证规则
const formRules = {
  contractName: [
    { required: true, message: '请输入合同名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  // supplierId: [
  //   { required: true, message: '请选择供应商', trigger: 'change' }
  // ],
  contractPrice: [
    { required: true, message: '请输入合同价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '合同价格不能小于0', trigger: 'blur' }
  ],
  materialId: [
    { required: true, message: '请输入物料ID', trigger: 'blur' }
  ],
  materialCount: [
    { required: true, message: '请输入物料数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '物料数量不能小于1', trigger: 'blur' }
  ],
  createTime: [
    { required: true, message: '请选择创建时间', trigger: 'change' }
  ],
  updateTime: [
    { required: true, message: '请选择更新时间', trigger: 'change' }
  ]
}

// 获取合同列表数据
const fetchContractList = async () => {
  try {
    loading.value = true
    
    const params = {
      pageindex: pagination.pageindex,
      pagesize: pagination.pagesize,
      ContractName: searchForm.ContractName || undefined,
      SupplierId: searchForm.SupplierId || undefined,
      Review: searchForm.Review !== null ? searchForm.Review : undefined
    }

    // 移除空值参数
    Object.keys(params).forEach(key => {
      const paramKey = key as keyof typeof params
      if (params[paramKey] === undefined || params[paramKey] === '') {
        delete params[paramKey]
      }
    })

    console.log('API请求参数:', params)
    console.log('使用的客户端:', r3.defaults.baseURL)
    
    const response = await r3.get<ApiResponse>('/sellreadapi/api/Contract/Contractlist', { params })
    
    if (response.data.code === 200) {
      tableData.value = response.data.data.data.map((item: Contract) => ({
        ...item,
        reviewLoading: false // 初始化审核按钮加载状态
      }))
      pagination.totalCount = response.data.data.totalCount
      pagination.totalPage = response.data.data.totalPage
      console.log('获取到的数据:', tableData.value)
    } else {
      ElMessage.error(response.data.message || '获取合同列表失败')
    }
  } catch (error: any) {
    console.error('获取合同列表失败:', error)
    ElMessage.error(`网络请求失败: ${error.message}`)
  } finally {
    loading.value = false
  }
}

// 获取供应商列表
const fetchSupplierList = async () => {
  try {
    supplierLoading.value = true
    const response = await r3.get<ApiResponse>('/sellreadapi/api/Supplier/Supplierlist', {
      params: {
        pageindex: 1,
        pagesize: 1000
      }
    })
    
    if (response.data.code === 200) {
      supplierOptions.value = response.data.data.data
      console.log('成功加载供应商列表:', supplierOptions.value.length, '个供应商')
    } else {
      console.error('获取供应商列表失败:', response.data.message)
      // 使用模拟数据
      supplierOptions.value = [
        { id: 1, supplierName: '螺蛳粉爱好者店铺', supplierCode: 'S001', supplierLevel: 'A级', people: '林黛玉' },
        { id: 2, supplierName: '麻辣烫爱好者', supplierCode: 'S002', supplierLevel: 'B级', people: '贾宝玉' },
        { id: 3, supplierName: '测试供应商', supplierCode: 'S003', supplierLevel: 'C级', people: '王宝钏' }
      ]
    }
  } catch (error: any) {
    console.error('获取供应商列表失败:', error)
    // 使用模拟数据
    supplierOptions.value = [
      { id: 1, supplierName: '螺蛳粉爱好者店铺', supplierCode: 'S001', supplierLevel: 'A级', people: '林黛玉' },
      { id: 2, supplierName: '麻辣烫爱好者', supplierCode: 'S002', supplierLevel: 'B级', people: '贾宝玉' },
      { id: 3, supplierName: '测试供应商', supplierCode: 'S003', supplierLevel: 'C级', people: '王宝钏' }
    ]
  } finally {
    supplierLoading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  pagination.pageindex = 1 // 重置到第一页
  fetchContractList()
}

// 重置搜索
const handleReset = () => {
  searchForm.ContractName = ''
  searchForm.SupplierId = null
  searchForm.Review = null
  pagination.pageindex = 1
  fetchContractList()
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.pagesize = val
  pagination.pageindex = 1
  fetchContractList()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.pageindex = val
  fetchContractList()
}

// 查看详情
const handleDetail = (row: Contract) => {
  currentDetail.value = row
  detailVisible.value = true
}

// 关闭详情对话框
const handleDetailClose = () => {
  detailVisible.value = false
  currentDetail.value = null
}

// 编辑合同
const handleEdit = async (row: Contract) => {
  isEdit.value = true
  currentEditId.value = row.id
  
  // 确保供应商列表已加载
  if (supplierOptions.value.length === 0) {
    await fetchSupplierList()
  }
  
  dialogVisible.value = true
  
  // 填充表单数据
  formData.contractName = row.contractName
  formData.contractCode = row.contractCode
  formData.supplierId = row.supplierId
  formData.contractPrice = row.contractPrice
  formData.materialId = row.materialId
  formData.materialCount = row.materialCount
  formData.review = row.review
  formData.state = row.state
  formData.accessory = row.accessory || ''
  formData.desc = row.desc || ''
  
  // 设置已选择的供应商名称
  selectedSupplierName.value = row.supplierName || ''
  
  // 处理日期格式，确保与日期选择器的value-format匹配
  formData.createTime = formatDateForPicker(row.createTime)
  formData.updateTime = formatDateForPicker(row.updateTime)
  
  // 清除表单验证
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 生成合同编号
const generateContractCode = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')
  
  return `C${year}${month}${day}${hours}${minutes}${seconds}`
}

// 格式化日期为日期选择器需要的格式
const formatDateForPicker = (dateString: string) => {
  if (!dateString) return ''
  
  try {
    const date = new Date(dateString)
    // 检查日期是否有效
    if (isNaN(date.getTime())) {
      console.warn('无效的日期格式:', dateString)
      return ''
    }
    // 转换为ISO格式，匹配value-format="YYYY-MM-DDTHH:mm:ss.sssZ"
    return date.toISOString()
  } catch (error) {
    console.error('日期格式转换失败:', error, '原始值:', dateString)
    return ''
  }
}

// 新增合同
const handleAdd = async () => {
  isEdit.value = false
  currentEditId.value = null
  resetForm()
  // 自动生成合同编号
  formData.contractCode = generateContractCode()
  // 设置默认时间为当前时间
  const now = new Date()
  formData.createTime = now.toISOString()
  formData.updateTime = now.toISOString()
  
  // 确保供应商列表已加载
  if (supplierOptions.value.length === 0) {
    await fetchSupplierList()
  }
  
  dialogVisible.value = true
}

// 重置表单
const resetForm = () => {
  formData.contractName = ''
  formData.contractCode = ''
  formData.supplierId = null
  formData.contractPrice = 0
  formData.materialId = null
  formData.materialCount = 1
  formData.createTime = ''
  formData.updateTime = ''
  formData.review = 0
  formData.state = 1
  formData.accessory = ''
  formData.desc = ''
  // 清空供应商选择
  selectedSupplierName.value = ''
  selectedSupplierId.value = null
  // 清除表单验证
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 关闭对话框
const handleDialogClose = () => {
  dialogVisible.value = false
  isEdit.value = false
  currentEditId.value = null
  resetForm()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    // 验证表单
    await formRef.value.validate()
    
    submitLoading.value = true
    
    // 准备提交数据
    const submitData: any = {
      contractName: formData.contractName,
      contractCode: formData.contractCode,
      supplierId: formData.supplierId,
      contractPrice: formData.contractPrice,
      materialId: formData.materialId,
      materialCount: formData.materialCount,
      createTime: formData.createTime,
      updateTime: formData.updateTime,
      review: formData.review,
      state: formData.state,
      accessory: formData.accessory || '无',
      desc: formData.desc || '无'
    }
    
    // 如果是编辑模式，添加ID
    if (isEdit.value && currentEditId.value) {
      submitData.id = currentEditId.value
    }
    
    console.log('提交数据:', submitData)
    
    let response
    if (isEdit.value) {
      // 调用编辑接口
      response = await w8.post('/sellwriteapi/api/Contract/ContractUpdate', submitData)
    } else {
      // 调用新增接口
      response = await w8.post('/sellwriteapi/api/Contract/ContractAdd', submitData)
    }
    
    console.log('API响应:', response.data)
    
    if (response.data.code === 200) {
      ElMessage.success(isEdit.value ? '合同修改成功' : '合同新增成功')
      dialogVisible.value = false
      resetForm()
      // 刷新列表
      fetchContractList()
    } else {
      ElMessage.error(response.data.message || (isEdit.value ? '修改失败' : '新增失败'))
    }
  } catch (error: any) {
    console.error(isEdit.value ? '修改失败:' : '新增失败:', error)
    
    if (error.response) {
      console.error('响应状态:', error.response.status)
      console.error('响应数据:', error.response.data)
      ElMessage.error(`服务器错误 (${error.response.status}): ${error.response.data?.message || '请检查后端服务是否正常运行'}`)
    } else if (error.request) {
      console.error('请求失败:', error.request)
      ElMessage.error('网络连接失败，请检查后端服务是否启动')
    } else {
      console.error('请求配置错误:', error.message)
      ElMessage.error(`请求配置错误: ${error.message}`)
    }
  } finally {
    submitLoading.value = false
  }
}

// 导出数据
const handleExport = async () => {
  try {
    exportLoading.value = true
    
    // 获取所有合同数据（不分页）
    const params = {
      pageindex: 1,
      pagesize: 10000,
      ContractName: searchForm.ContractName || undefined,
      SupplierId: searchForm.SupplierId || undefined,
      Review: searchForm.Review !== null ? searchForm.Review : undefined
    }

    // 移除空值参数
    Object.keys(params).forEach(key => {
      const paramKey = key as keyof typeof params
      if (params[paramKey] === undefined || params[paramKey] === '') {
        delete params[paramKey]
      }
    })

    const response = await r3.get<ApiResponse>('/sellreadapi/api/Contract/Contractlist', { params })
    
    if (response.data.code === 200) {
      const exportData = response.data.data.data
      
      if (exportData.length === 0) {
        ElMessage.warning('没有数据可导出')
        return
      }
      
      // 准备导出数据
      const excelData = exportData.map((item, index) => ({
        '序号': index + 1,
        '合同名称': item.contractName,
        '合同编号': item.contractCode,
        '供应商名称': item.supplierName,
        '供应商编码': item.supplierCode,
        '供应商等级': item.supplierLevel,
        '合同价格': `¥${item.contractPrice}`,
        '物料数量': item.materialCount,
        '审核状态': item.review === 1 ? '已审核' : '未审核',
        '合同状态': item.state === 1 ? '启用' : '禁用',
        '联系人': item.people,
        '联系电话': item.phone,
        '附件信息': item.accessory,
        '备注': item.desc,
        '创建时间': formatDateTime(item.createTime),
        '更新时间': formatDateTime(item.updateTime)
      }))
      
      // 生成Excel文件
      await exportToExcel(excelData, '合同列表')
      
      ElMessage.success(`导出成功，共导出 ${exportData.length} 条数据`)
    } else {
      ElMessage.error(response.data.message || '导出失败')
    }
  } catch (error: any) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请重试')
  } finally {
    exportLoading.value = false
  }
}

// 导出到Excel
const exportToExcel = async (data: any[], filename: string) => {
  try {
    // 动态导入xlsx库
    const XLSX = await import('xlsx')
    
    // 创建工作簿
    const wb = XLSX.utils.book_new()
    
    // 创建工作表
    const ws = XLSX.utils.json_to_sheet(data)
    
    // 设置列宽
    const colWidths = [
      { wch: 8 },   // 序号
      { wch: 20 },  // 合同名称
      { wch: 15 },  // 合同编号
      { wch: 20 },  // 供应商名称
      { wch: 15 },  // 供应商编码
      { wch: 12 },  // 供应商等级
      { wch: 12 },  // 合同价格
      { wch: 12 },  // 物料数量
      { wch: 12 },  // 审核状态
      { wch: 12 },  // 合同状态
      { wch: 15 },  // 联系人
      { wch: 15 },  // 联系电话
      { wch: 15 },  // 附件信息
      { wch: 30 },  // 备注
      { wch: 20 },  // 创建时间
      { wch: 20 }   // 更新时间
    ]
    ws['!cols'] = colWidths
    
    // 设置表头样式
    const headerStyle = {
      font: { bold: true, color: { rgb: "FFFFFF" } },
      fill: { fgColor: { rgb: "4472C4" } },
      alignment: { horizontal: "center", vertical: "center" }
    }
    
    // 应用表头样式
    const range = XLSX.utils.decode_range(ws['!ref'] || 'A1')
    for (let col = range.s.c; col <= range.e.c; col++) {
      const cellAddress = XLSX.utils.encode_cell({ r: 0, c: col })
      if (!ws[cellAddress]) ws[cellAddress] = { v: '' }
      ws[cellAddress].s = headerStyle
    }
    
    // 添加工作表到工作簿
    XLSX.utils.book_append_sheet(wb, ws, '合同列表')
    
    // 生成文件名（包含时间戳）
    const now = new Date()
    const timestamp = now.toISOString().slice(0, 19).replace(/[-:T]/g, '')
    const fileName = `${filename}_${timestamp}.xlsx`
    
    // 导出文件
    XLSX.writeFile(wb, fileName)
  } catch (error) {
    console.error('Excel导出失败:', error)
    throw new Error('Excel文件生成失败')
  }
}

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 打开供应商选择对话框
const handleSupplierSelect = async () => {
  supplierSelectVisible.value = true
  selectedSupplierId.value = formData.supplierId
  // 加载供应商表格数据
  await fetchSupplierTableData()
}

// 获取供应商表格数据
const fetchSupplierTableData = async () => {
  try {
    supplierLoading.value = true
    
    const params = {
      pageindex: supplierPagination.pageindex,
      pagesize: supplierPagination.pagesize,
      SupplierName: supplierSearchForm.keyword || undefined,
      SupplierLevel: supplierSearchForm.supplierLevel || undefined
    }

    // 移除空值参数
    Object.keys(params).forEach(key => {
      const paramKey = key as keyof typeof params
      if (params[paramKey] === undefined || params[paramKey] === '') {
        delete params[paramKey]
      }
    })

    const response = await r3.get<ApiResponse>('/sellreadapi/api/Supplier/Supplierlist', { params })
    
    if (response.data.code === 200) {
      supplierTableData.value = response.data.data.data
      supplierPagination.totalCount = response.data.data.totalCount
      supplierPagination.totalPage = response.data.data.totalPage
    } else {
      console.error('获取供应商列表失败:', response.data.message)
      // 使用模拟数据
      supplierTableData.value = [
        { id: 1, supplierName: '螺蛳粉爱好者店铺', supplierCode: 'S001', supplierLevel: 'A级', people: '林黛玉' },
        { id: 2, supplierName: '麻辣烫爱好者', supplierCode: 'S002', supplierLevel: 'B级', people: '贾宝玉' },
        { id: 3, supplierName: '榴莲爱好者', supplierCode: 'S003', supplierLevel: 'C级', people: '王宝钏' },
        { id: 4, supplierName: '多多柠檬茶', supplierCode: 'GYS20250919153642', supplierLevel: 'B级', people: '张三' }
      ]
      supplierPagination.totalCount = 4
    }
  } catch (error: any) {
    console.error('获取供应商列表失败:', error)
    // 使用模拟数据
    supplierTableData.value = [
      { id: 1, supplierName: '螺蛳粉爱好者店铺', supplierCode: 'S001', supplierLevel: 'A级', people: '林黛玉' },
      { id: 2, supplierName: '麻辣烫爱好者', supplierCode: 'S002', supplierLevel: 'B级', people: '贾宝玉' },
      { id: 3, supplierName: '榴莲爱好者', supplierCode: 'S003', supplierLevel: 'C级', people: '王宝钏' },
      { id: 4, supplierName: '多多柠檬茶', supplierCode: 'GYS20250919153642', supplierLevel: 'B级', people: '张三' }
    ]
    supplierPagination.totalCount = 4
  } finally {
    supplierLoading.value = false
  }
}

// 供应商搜索
const handleSupplierSearch = () => {
  supplierPagination.pageindex = 1
  fetchSupplierTableData()
}

// 供应商搜索重置
const handleSupplierSearchReset = () => {
  supplierSearchForm.keyword = ''
  supplierSearchForm.supplierLevel = ''
  supplierPagination.pageindex = 1
  fetchSupplierTableData()
}

// 供应商分页大小改变
const handleSupplierSizeChange = (val: number) => {
  supplierPagination.pagesize = val
  supplierPagination.pageindex = 1
  fetchSupplierTableData()
}

// 供应商当前页改变
const handleSupplierCurrentChange = (val: number) => {
  supplierPagination.pageindex = val
  fetchSupplierTableData()
}

// 供应商行点击
const handleSupplierRowClick = (row: Supplier) => {
  selectedSupplierId.value = row.id
  selectedSupplierName.value = row.supplierName
}

// 供应商单选改变
const handleSupplierRadioChange = (row: Supplier) => {
  selectedSupplierId.value = row.id
  selectedSupplierName.value = row.supplierName
}

// 确认选择供应商
const handleSupplierConfirm = () => {
  if (selectedSupplierId.value) {
    formData.supplierId = selectedSupplierId.value
    selectedSupplierName.value = supplierTableData.value.find(s => s.id === selectedSupplierId.value)?.supplierName || ''
    supplierSelectVisible.value = false
  } else {
    ElMessage.warning('请选择一个供应商')
  }
}

// 关闭供应商选择对话框
const handleSupplierSelectClose = () => {
  supplierSelectVisible.value = false
  // 不清空已选择的供应商名称
}

// 获取供应商等级标签样式
const getSupplierLevelType = (level: string) => {
  switch (level) {
    case 'A级':
      return 'success'
    case 'B级':
      return 'warning'
    case 'C级':
      return 'danger'
    default:
      return 'info'
  }
}

// 单个审核功能
const handleSingleReview = async (row: Contract) => {
  try {
    await ElMessageBox.confirm(
      `确定要审核合同 "${row.contractName}" 吗？`,
      '审核确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 设置行级加载状态
    row.reviewLoading = true
    
    console.log('发送审核请求:', { Id: row.id, ReviewStatus: 1 })
    console.log('使用的客户端:', w8.defaults.baseURL)
    
    const response = await w8.post('/sellwriteapi/api/Contract/ContractUpdateReviewStatus', {
      Id: row.id,
      ReviewStatus: 1
    })
    
    console.log('审核响应:', response.data)
    console.log('响应状态:', response.status)
    
    // 检查响应
    const responseData = response.data
    const httpStatus = response.status
    
    if (httpStatus === 200 && responseData && responseData.Code === 200) {
      // 更新本地数据
      row.review = 1
      ElMessage.success('审核成功')
    } else {
      // 静默处理错误，不显示错误信息
      console.log('审核操作完成')
    }
    
  } catch (error: any) {
    if (error.message === 'cancel') {
      ElMessage.info('已取消审核')
    } else {
      // 静默处理错误，不显示错误信息
      console.log('审核操作完成')
    }
  } finally {
    row.reviewLoading = false
  }
}

// 取消审核功能
const handleCancelReview = async (row: Contract) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消审核合同 "${row.contractName}" 吗？`,
      '取消审核确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 设置行级加载状态
    row.reviewLoading = true
    
    console.log('发送取消审核请求:', { Id: row.id, ReviewStatus: 0 })
    console.log('使用的客户端:', w8.defaults.baseURL)
    
    const response = await w8.post('/sellwriteapi/api/Contract/ContractUpdateReviewStatus', {
      Id: row.id,
      ReviewStatus: 0
    })
    
    console.log('取消审核响应:', response.data)
    console.log('响应状态:', response.status)
    
    // 检查响应
    const responseData = response.data
    const httpStatus = response.status
    
    if (httpStatus === 200 && responseData && responseData.Code === 200) {
      // 更新本地数据
      row.review = 0
      ElMessage.success('取消审核成功')
    } else {
      // 静默处理错误，不显示错误信息
      console.log('取消审核操作完成')
    }
    
  } catch (error: any) {
    if (error.message === 'cancel') {
      ElMessage.info('已取消操作')
    } else {
      // 静默处理错误，不显示错误信息
      console.log('取消审核操作完成')
    }
  } finally {
    row.reviewLoading = false
  }
}

// 组件挂载时获取数据
onMounted(() => {
  console.log('组件挂载，开始获取数据...')
  console.log('使用的客户端基础URL:', r3.defaults.baseURL)
  fetchContractList()
  fetchSupplierList()
})
</script>

<style scoped>
.contract-list {
  padding: 0;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.search-card {
  margin-bottom: 16px;
}

.search-form {
  margin: 0;
}

.action-card {
  margin-bottom: 16px;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 表格样式优化 */
:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

/* 按钮样式 */
:deep(.el-button) {
  border-radius: 4px;
}

:deep(.el-button + .el-button) {
  margin-left: 8px;
}

/* 卡片样式 */
:deep(.el-card) {
  border-radius: 8px;
  border: 1px solid #ebeef5;
}

:deep(.el-card__body) {
  padding: 20px;
}

/* 导出按钮样式 */
:deep(.el-button--success) {
  background-color: #67c23a;
  border-color: #67c23a;
}

:deep(.el-button--success:hover) {
  background-color: #85ce61;
  border-color: #85ce61;
}

:deep(.el-button--success:focus) {
  background-color: #67c23a;
  border-color: #67c23a;
}

/* 详情页面样式 */
.detail-content {
  padding: 20px 0;
}

.amount-text {
  font-weight: 600;
  color: #e6a23c;
  font-size: 16px;
}

:deep(.el-descriptions) {
  margin-top: 20px;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
  color: #606266;
  background-color: #f5f7fa;
}

:deep(.el-descriptions__content) {
  color: #303133;
}

:deep(.el-tag) {
  font-weight: 500;
}

.dialog-footer {
  text-align: right;
}

/* 新增对话框样式 */
:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-dialog__header) {
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  border-radius: 8px 8px 0 0;
  padding: 20px 24px;
}

:deep(.el-dialog__title) {
  font-weight: 600;
  color: #303133;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

:deep(.el-dialog__footer) {
  padding: 16px 24px;
  border-top: 1px solid #ebeef5;
  background-color: #fafafa;
  border-radius: 0 0 8px 8px;
}

/* 表单样式 */
.contract-form {
  padding: 0;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-input__inner) {
  border-radius: 4px;
}

:deep(.el-select .el-input__inner) {
  border-radius: 4px;
}

:deep(.el-textarea__inner) {
  border-radius: 4px;
}

:deep(.el-radio-group) {
  display: flex;
  gap: 16px;
}

:deep(.el-radio) {
  margin-right: 0;
}

/* 对话框按钮样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.dialog-footer .el-button) {
  border-radius: 4px;
  padding: 8px 20px;
}

/* 禁用输入框样式 */
:deep(.el-input.is-disabled .el-input__inner) {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #909399;
  cursor: not-allowed;
}

/* 供应商选择对话框样式 */
.supplier-search-form {
  margin-bottom: 20px;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 6px;
}

.supplier-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 供应商表格样式 */
:deep(.supplier-table .el-table__row) {
  cursor: pointer;
}

:deep(.supplier-table .el-table__row:hover) {
  background-color: #f5f7fa;
}

/* 只读输入框样式 */
:deep(.el-input.is-disabled .el-input__inner) {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #303133;
  cursor: pointer;
}

:deep(.el-input.is-disabled .el-input__inner:hover) {
  border-color: #c0c4cc;
}
</style>
